package vip.zhenzicheng.nettybasic.splicing.demo;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.net.InetSocketAddress;

/**
 * 客户端
 *
 * @author zhenzicheng
 * @date 2022-06-24 09:24
 */
public class EchoCliStickyHalf {

  private final int port;
  private final String host;

  public EchoCliStickyHalf(int port, String host) {
    this.port = port;
    this.host = host;
  }

  public static void main(String[] args) throws InterruptedException {
    new EchoCliStickyHalf(9999, "127.0.0.1").start();
  }

  public void start() throws InterruptedException {

    /*线程组*/
    EventLoopGroup group = new NioEventLoopGroup();
    try {
      /*客户端启动必备，和服务器的不同点*/
      Bootstrap b = new Bootstrap();
      b.group(group)
          .channel(NioSocketChannel.class)
          .remoteAddress(new InetSocketAddress(host, port))
          .handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
              ch.pipeline().addLast(new EchoCliSHHandler());

            }
          });
      /*异步连接到服务器，sync()会阻塞到完成，和服务器的不同点*/
      ChannelFuture f = b.connect().sync();
      f.channel().closeFuture().sync();/*阻塞当前线程，直到客户端的Channel被关闭*/
    } finally {
      group.shutdownGracefully().sync();
    }
  }
}
